from rest_framework import serializers
from .models import Communitys, Comments, upvote

from .utils.b64 import bs64_decoded

class CommunitySerializer(serializers.ModelSerializer):
    class Meta:
        model = Communitys
        fields = ('id', 'title', 'image1','image2','image3','content','create_time','giveLike')


'''
自定义序列化器，用于返回社区和评论
'''
class ComentsSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M')
    class Meta:
        model = Comments
        fields = ('id', 'content', 'create_time', 'user_id')
        depth = 1


class CommunitySerializerComents(serializers.ModelSerializer):
    comments_Com = ComentsSerializer(many=True, read_only=True)
    class Meta:
        model = Communitys
        fields = ('id', 'title', 'image1', 'image2', 'image3', 'content', 'create_time', 'giveLike', 'comments_Com', 'user_id')
        depth = 1




'''
自定义序列化器，用于返回用户点赞状态
'''
class upvoteSerializer(serializers.ModelSerializer):
    user_upvote_status = serializers.SerializerMethodField()  # 自定义字段名
    class Meta:
        model = upvote
        fields = ('user_upvote_status',)

    def get_user_upvote_status(self, obj):
        # 从序列化器的上下文中获取当前用户（假设你已经以某种方式将用户传递给了序列化器）
        user = bs64_decoded(self.context.get('request').COOKIES.get("user_id"))  # 序列化时传递了 request 对象作为上下文,获取到了user_id

        # 这里我们假设 user_upvote 是一个关联到 User 模型的字段
        if obj.user_upvote.id == int(user):
            # 如果当前用户是点赞者，返回某种状态
            return {"likeStatus": obj.likeStatus, 'community_id':obj.community.id}
        else:
            # 如果没有人点赞
            return None

class ComentsSerializervote(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M')
    class Meta:
        model = Comments
        fields = ('id', 'content', 'create_time', 'user_id')
        depth = 1


class CommunitySerializerComentsvote(serializers.ModelSerializer):
    comments_Com = ComentsSerializervote(many=True, read_only=True)
    community_upvote_object = upvoteSerializer(many=True, read_only=True)
    class Meta:
        model = Communitys
        fields = ('id', 'title', 'image1', 'image2', 'image3', 'content', 'create_time', 'giveLike', 'comments_Com', 'user_id', 'community_upvote_object')
        depth = 1